import os

try:
    # 可能引发异常的代码
    result = 10 / 0
except ZeroDivisionError:
    # 处理特定异常
    print("不能除以零!")

    try:
        file = open("example.txt", "r")
        content = file.read()
        number = int(content)
        print(f"文件中的数字是: {number}")
    except FileNotFoundError:
        print("文件未找到!")
    except ValueError:
        print("文件内容不是有效的数字!")
    finally:
        print("执行清理操作...")
        if 'file' in locals() and not file.closed:
            file.close()




try:
    age = int(input("请输入您的年龄: "))
    if age < 0:
        raise ValueError("年龄不能为负数")
    print(f"您的年龄是: {age}")
except ValueError as ve:
    print(f"输入无效: {ve}")



try:
    with open("nonexistent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("文件不存在，请检查文件名!")




try:
    my_list = [1, 2, 3]
    print(my_list[5])
except IndexError:
    print("列表索引超出范围!")



try:
    my_dict = {"name": "Alice", "age": 25}
    print(my_dict["address"])
except KeyError:
    print("字典中不存在该键!")






try:
    result = "10" + 5
except TypeError:
    print("不能将字符串和整数相加!")





try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零!")





try:
    # 可能引发多种异常的代码
    pass
except (ValueError, TypeError) as e:
    print(f"发生了值或类型错误: {e}")




try:
    num = int("abc")
except ValueError as e:
    print(f"错误信息: {e}")
    print(f"异常类型: {type(e).__name__}")






try:
    result = 10 / 2
except ZeroDivisionError:
    print("除零错误!")
else:
    print(f"计算结果: {result}")  # 仅在try块成功执行时运行
finally:
    print("执行完成")





class NegativeNumberError(Exception):
    """自定义异常类"""
    pass

try:
    num = int(input("输入正数: "))
    if num < 0:
        raise NegativeNumberError("不允许负数")
except NegativeNumberError as ne:
    print(ne)










def safe_read_file(filepath):
    """安全读取文本文件"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print(f"错误：文件 {filepath} 不存在")
        return None
    except PermissionError:
        print(f"错误：没有权限读取文件 {filepath}")
        return None
    except UnicodeDecodeError:
        print(f"错误：文件 {filepath} 编码不兼容")
        return None
    except Exception as e:
        print(f"读取文件时发生未知错误: {e}")
        return None

# 使用示例
content = safe_read_file("data.txt")
if content:
    print("文件内容:", content[:100])  # 只打印前100字符


def read_large_file_safely(filepath, max_size=1024 * 1024):
    """安全读取大文件（限制文件大小）"""
    try:
        # 检查文件大小
        file_size = os.path.getsize(filepath)
        if file_size > max_size:
            raise SecurityError(f"文件过大（{file_size}字节），超过限制{max_size}字节")

        # 检查文件类型（简单版）
        if not filepath.endswith('.txt'):
            raise SecurityError("只允许读取文本文件(.txt)")

        # 实际读取
        with open(filepath, 'r', encoding='utf-8') as f:
            return f.read()

    except FileNotFoundError:
        print(f"文件 {filepath} 不存在")
    except PermissionError:
        print("没有文件访问权限")
    except SecurityError as e:
        print(f"安全限制: {e}")
    except Exception as e:
        print(f"读取错误: {e}")
    return None


class SecurityError(Exception):
    """自定义安全异常"""
    pass


# 使用示例
content = read_large_file_safely("data.txt")

import json
import yaml  # 需要安装pyyaml: pip install pyyaml


def read_config_safely(filepath):
    """安全读取配置文件"""
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"配置文件 {filepath} 不存在")

    if not filepath.endswith(('.json', '.yaml', '.yml')):
        raise ValueError("只支持JSON或YAML配置文件")

    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            if filepath.endswith('.json'):
                return json.load(f)
            else:
                return yaml.safe_load(f)  # 使用safe_load避免任意代码执行
    except (json.JSONDecodeError, yaml.YAMLError) as e:
        print(f"配置文件格式错误: {e}")
        return None
    except Exception as e:
        print(f"读取配置时出错: {e}")
        return None


# 使用示例
config = read_config_safely("app_config.json")
if config:
    print("数据库配置:", config.get('database', {}))

import logging
from pathlib import Path


def setup_logging():
    """配置日志系统"""
    log_file = Path("calculator.log")
    logging.basicConfig(
        filename=log_file,
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    # 限制日志文件大小
    if log_file.exists() and log_file.stat().st_size > 1_000_000:  # 1MB
        log_file.unlink()


def logged_calculator():
    """带日志记录的计算器"""
    setup_logging()

    while True:
        try:
            num1 = float(input("第一个数字: "))
            op = input("运算符(+, -, *, /): ")
            num2 = float(input("第二个数字: "))

            if op not in ('+', '-', '*', '/'):
                raise ValueError("无效运算符")
            if op == '/' and num2 == 0:
                raise ZeroDivisionError("除零错误")

            # 执行计算
            if op == '+':
                result = num1 + num2
            elif op == '-':
                result = num1 - num2
            elif op == '*':
                result = num1 * num2
            else:
                result = num1 / num2

            # 记录成功计算
            logging.info(f"{num1}{op}{num2}={result}")
            print(f"结果: {result:.2f}")

        except ValueError as e:
            logging.warning(f"输入错误: {e}")
            print(f"错误: {e}")
        except ZeroDivisionError as e:
            logging.error(f"计算错误: {e}")
            print(f"错误: {e}")
        except Exception as e:
            logging.critical(f"未知错误: {e}", exc_info=True)
            print("发生严重错误，已记录")

        if input("继续吗？(y/n) ").lower() != 'y':
            break


# 使用示例
logged_calculator()